<?php

/*
 * 物业端用户信息操作
 */

namespace App\Http\Controllers\Property;


use App\Common\json;
use App\Common\SmsClient;
use App\Http\Controllers\Controller;
use App\Libraries\UploadApp;
use App\Libraries\upload;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Common\sms;

class UserController extends Controller{

    private $app_key = 'mukitech#property';

    private $client_id = 'YXA6Pg1NUFVgEeeSPLWHHH_FuA';

    private $client_secret = 'YXA6WoQYtntuK5I0ueC-8RJG62BDi_s';

    private $url = "https://a1.easemob.com/mukitech/property";

    private    $sms_url 		= "http://www.api.zthysms.com/sendSms.do";//提交地址
    private    $username 	    = "nbsqyl2017hy";//用户名
    private    $password 	    = "ZTnbsqyl20178520";//原密码



    function __construct()
    {
        $url = $this->url . "/token";
        $data = array(
            'grant_type' => 'client_credentials',
            'client_id' => $this->client_id,
            'client_secret' => $this->client_secret
        );
        $rs = json_decode($this->curl($url, $data), true);
        $this->token = $rs['access_token'];
    }

    public function smscode($phone,$rand){
        $sms = new SmsClient($this->sms_url,$this ->username, $this->password);
        $data = array(
            'content' 	=> "小主，您正在加入智慧生态社区栖云里，验证码:$rand,请妥善保管，这是我们之间的约定哦 【栖云里】",//短信内容
            'mobile' 	=> $phone,//手机号码
            'productid' => '887361',//产品id
            'xh'		=> ''//小号
        );
        $sms ->data = $data;
       return  $value  = $sms ->sendSMS('post');
    }

    public function Select(Request $request){
        if($request ->isMethod('post')){
            $mphone  = $request ->input('phone');
            $data = DB::table('user')->select('phone')->where('phone', '=', $mphone)->get();
            $Array     = (object)array();
            if ($data == true) {
                return json::json('success', '手机号已经被注册', $Array);
            } else {
                return json::json('failure', '手机号可以注册', $Array);
            }
        }
    }

    //发送验证码
    public function send(Request $request)
    {
        if($request ->isMethod('post')) {
            $Array    = (object)array();
            $rand = rand(1000, 9999);
            $mphone  = $request ->input('phone');
            $select    = DB::table('user') ->where('phone',$mphone)->where('user_operation',0)->get();
            if($select == true){
                $Arr      = (object)array();
                return json::json('failure', '用户已经注册', $Arr);
            }else{
                $this ->smscode($mphone,$rand);
                $value  = array('code' =>$rand);
                return json::json('success', '验证码发送成功', $value);
            }

        }
    }

    //忘记密码发送验证码
    public function sms(Request $request){
        if($request ->isMethod('post')) {
            $Array    = (object)array();
            $rand = rand(1000, 9999);
            $mphone  = $request ->input('phone');
            $this ->smscode($mphone,$rand);
            $value  = array('code' =>$rand);
            return json::json('success', '验证码发送成功', $value);
        }
    }

    public function uploade(Request $request){
        if($request ->isMethod('post')){
            $file     = $request ->input('file');
            $upload     = new UploadApp();
            $data = array();
            foreach ($file as $key => $value){
                foreach ($value as $k  => $v){
                    $data[$k][$key]     = $v;
                }
            }
            var_dump($data);
            /* for ($i = 0; $i < count($data); $i++) {*/
            $positive = $upload->upload($file, date('Ymdhis'));

            /* }*/

        }
    }



    /*
     * 注册
     */
    public function register(Request $request){
        if($request  ->isMethod('post')){
            $empty_array = (object)array();
            $phone     = $request ->input('phone');
            $pass      = $request ->input('pass');
            $code      = $request -> input('code');
            $nickname  = rand(10000000000,99999999999);
            $time      = date('Y-m-d H:i:s');
            if($phone =='' || $pass == ''){
                return json::json('100','提交时存在空值',$empty_array);
            }
            $select    = DB::table('user') ->where('phone',$phone)->where('user_operation',0)->get();
            if($select == true){
                $Arr      = (object)array();
                return json::json('failure', '用户已经注册', $Arr);
            }else {
                $select1    = DB::table('user') ->where('phone',$phone)->where('user_operation',1)->get();
                  if($select1 == true){
                       $update   = DB::table('user')->where('phone',$phone)->update(
                           ['pass' =>$pass,
                               'user_operation' =>0
                           ]
                       );
                   }else {
                    $update = DB::table('user')
                        ->select('phone', 'pass','user_create_time')
                        ->insert([
                            'nickname' =>$nickname,
                            'phone' => $phone,
                            'pass' => $pass,
                            'user_status' =>2,
                            'user_invitation' => $code,
                            'user_create_time' => $time
                        ]);
                }
                if ($update == true) {
                    $select = DB::table('user')->where('phone', $phone)->get();
                    foreach ($select as $value) {
                        $dd = array('user_id' => $value->user_id, 'phone' => $value->phone, 'pass' => $value->pass);
                    }
                    $this->hx_register($phone, $pass, $phone);
                    return json::json('success', '恭喜您注册成功', $dd);
                } else {
                    return json::json('failure', '由于网络或者不正当原因注册失败', $empty_array);
                }
            }
        }else{
            return json::json('101','提交方式错误','');
        }
    }

    /*
         * 登录
         */
    public function login(Request $request){
        if($request -> isMethod('post')){
            $empty_array    = (object)array();
            $phone     = $request ->input('phone');
            $pass      = $request ->input('pass');
            /* if(empty($pass) || empty($pass)){
                 return json::json('100','提交时存在空值','');
             }*/
            $data     = DB::table('user')
                ->select('user_id','phone','head','nickname','real_name','sex',
                    'sign','identity','user_address','user_village',
                    'floor','number','room','village_name','user_status','user_roomname')
                ->leftjoin('village','user.user_village','=','village.village_id')
                ->leftjoin('village_rooms','village.village_id','=','village_rooms.rooms_village')
                ->where('phone',$phone)
                ->where('pass',$pass)
                ->where('user_operation',0)
                ->where('user_type',0)
                ->get();
            if($data  == true){
                foreach ($data as $value) {
                    $key = array(
                        'user_id' => $value->user_id,
                        'phone' => $value->phone,
                        'head' => $value->head,
                        'nickname' => $value->nickname,
                        'real_name' =>$value ->real_name,
                        'sex' => $value->sex,
                        'sign' => $value->sign,
                        'identity' => $value->identity,
                        'user_address' => $value->user_address,
                        'village_name'     =>$value->village_name,
                        'village_id' => $value->user_village,
                       'user_roomname' =>$value ->user_roomname,
                       /* 'floor' => $value->floor,
                        'number' => $value->number,
                        'room'   =>$value ->room,*/
                        'user_status' =>$value ->user_status
                    );
                }
                }
            if($data  == true){
                return json::json('success','恭喜您登录成功',$key);
            }else{
                return json::json('failure','用户名或者密码错误',$empty_array);
            }
        }else{
            return json::json('101','提交方式错误','');
        }
    }
    /*
     * 修改密码
     */
    /* public function revise(Request $request){
         if($request ->isMethod('post')){
             $phone       = trim($request ->input('phone'));
             $pass        = trim($request ->input('pass'));
             if(isset($pass) || isset($pass)){
                 return json::json('100','提交时存在空值','');
             }
             $data       = DB::table('user')
                         ->where('phone',$phone)
                         ->update([
                             'pass'     => $pass
                         ]);
             if($data   == true){
                 return json::json('1','恭喜您密码修改成功','');
             }else{
                 return json::json('0','由于网络或者不正当原因注册失败','');
             }
         }else{
             return json::json('101','提交方式错误','');
         }
     }*/


    /**忘记密码*/
    public function forget(Request $request){
        if($request ->isMethod('post')){
            $empty_array = (object)array();
            $phone    = trim($request ->input('phone'));
            $newpass  = trim($request ->input('newpass'));
          //  $code     = trim($request ->input('code'));
            $affirmpass = trim($request ->input('affirmpass'));
            /*            if($affirmpass != $newpass){
                            return json::json('failure','两次密码不一样',$empty_array);
                        }*/
                        $update    = DB::table('user')
                            ->where('phone',$phone)
                            ->select('phone')
                            ->update(['pass'=>$affirmpass,'user_update_time'=>date('Y-m-d H:i:s')]);
                        if($update  == true){
                            $this ->hx_user_update_password($phone,$affirmpass);
                            return json::json('success','恭喜您修改成功',$empty_array);
                        }else{
                            return json::json('failure','输入的密码与原密码相同不能修改',$empty_array);

                        }
        }else{
            return json::json('101','提交方式错误','');
        }
    }


    /*添加用户信息*/
    public function add_userinfo(Request $request){
        if($request  ->isMethod('post')){
            $array          = (object)array();
            $id      = trim($request ->input('user_id'));
            $head    = trim($request->input('head'));
            $nickname = trim($request ->input('nickname')); //呢称*/
            $real_name = trim($request ->input('real_name')); //呢称*/
            $sex     = trim($request ->input('sex'));        //性别
            $sign    = trim($request ->input('sign'));       //个性签名
            $identity = trim($request ->input('identity'));  //业主身份*/
            $address    = trim($request ->input('address'));
            $village_id = trim($request ->input('village_id'));    //小区ID
            $user_roomname = trim($request ->input('user_roomname'));    //小区ID
            $time       = $request ->input('Y-m-d H:i:s');
            $select_data  = DB::table('user') ->select('user_status')->where('user_id',$id) ->first();
            if($select_data ->user_status ==1){
                $data      = DB::table('user')
                    ->where('user_id',$id)
                    ->update([
                        'head'       => $head,
                        'nickname'    => $nickname,
                        'sex'         => $sex,
                        'sign'        => $sign,
                        'identity'    => $identity,
                        'user_address'     => $address,
                        'user_village'   => $village_id,
                        'user_roomname' =>$user_roomname,
                        'real_name'=>$real_name,
                        /*          'floor'        => $floor,
                                  'number'       => $number,
                                  'room'         => $room,*/
                        'user_create_time' => $time
                    ]);
            }else{
                $data      = DB::table('user')
                    ->where('user_id',$id)
                    ->update([
                        'head'       => $head,
                        'nickname'    => $nickname,
                        'sex'         => $sex,
                        'sign'        => $sign,
                        'identity'    => $identity,
                        'user_address'     => $address,
                        'user_village'   => $village_id,
                        'user_roomname' =>$user_roomname,
                        'real_name'=>$real_name,
                        'user_status' =>0,
                        /*          'floor'        => $floor,
                                  'number'       => $number,
                                  'room'         => $room,*/
                        'user_create_time' => $time
                    ]);
            }


            if($data  == true){
                $select       = DB::table('user')
                    ->leftjoin('village','user.user_village','=','village.village_id')
                    ->where('user_id',$id)
                    ->first();
                $dd           = DB::table('address') ->where('user_address',$id)->where('judge_user',1)->get();
                if($dd  == true){
                    DB::table('address') ->where('user_address',$id)->where('judge_user',1)->update([
                        'name'=>$nickname,'phone'=>$select->phone,'province'=>$address,'address'=>$select->village_name.$user_roomname

                    ]);
                }else{
                    DB::table('address') ->insert([
                        'user_address'  =>$id,
                        'name'=>$nickname,'phone'=>$select->phone,'province'=>$address,'address'=>$select->village_name.$user_roomname,
                        'start'  =>0,'judge_user'=>1
                    ]);
                }
                return json::json('success','恭喜您数据更新成功',$array);
            }else{
                return json::json('failure','对不起,您都没有修改任何参数,更新失败',$array);
            }
        }else{
            return json::json('101','提交方式错误','');
        }
    }


    /*展示用户信息*/
    public function show_userinfo(Request $request){
        if($request ->isMethod('post')){
            $Array   = (object)array();
            $id      = trim($request ->input('user_id'));
            if(empty($id)){
                return json::json('100','提交时存在空值',json::value(1));
            }
            $data   = DB::table('user')
                ->select('phone','head','nickname','real_name','sex',
                    'sign','identity','user_address','floor','number',
                    'room','village_name','user_village','user_id','user_roomname')
                ->leftjoin('village','user.user_village','=','village.village_id')
                ->where('user_id',$id)
                ->get();
            foreach ($data as $value){
                $da                    = array(
                    'user_id'         =>$value->user_id,
                    'phone'           =>$value->phone,
                    'head'            =>$value->head,
                    'nickname'        =>$value->nickname,
                    'real_name'       =>$value ->real_name,
                    'sex'     =>$value->sex,
                    'village_id'=>$value->user_village,
                    'sign'            =>$value->sign,
                    'identity'        =>$value->identity,
                    'address'         =>$value->user_address,
                    'village_name'     =>$value->village_name,
                    'user_roomname' =>$value ->user_roomname,

/*                    'floor'           =>$value->floor,
                    'number'          =>$value->number,
                    'room'            =>$value->room*/
                );
            }
            if($data == true){
                return json::json('success','恭喜您数据获取成功',$da);
            }else{
                return json::json('failure','获取数据失败',$Array);
            }
        }else{
            return json::json('101','提交方式错误','');
        }
    }

    //获取全部用户
    public function userwhole(Request $request){
        if($request ->isMethod('get')){
            $Array  = [];
            $data    = DB::table('user')
                ->select('user_id','phone','head','nickname','real_name','sex',
                    'sign','identity','user_address','user_village',
                    'floor','number','room','village_name','user_roomname')
                ->leftjoin('village','user.user_village','=','village.village_id')
                ->get();
            foreach ($data as $value){
                $da[]                    = array(
                    'user_id'         =>$value->user_id,
                    'phone'           =>$value->phone,
                    'head'            =>$value->head,
                    'nickname'        =>$value->nickname,
                    'real_name'       =>$value ->real_name,
                    'sex'     =>$value->sex,
                    'village_id'=>$value->user_village,
                    'sign'            =>$value->sign,
                    'identity'        =>$value->identity,
                    'address'         =>$value->user_address,
                    'village_name'     =>$value->village_name,
                    'user_roomname' =>$value ->user_roomname,
/*                    'floor'           =>$value->floor,
                    'number'          =>$value->number,
                    'room'            =>$value->room*/
                );
            }
            if($data == true){
                return json::json('success','恭喜您数据获取成功',$da);
            }else{
                return json::json('failure','获取数据失败',$Array);
            }
        }else{
            return json::json('101','提交方式错误','');
        }
    }

    public function loign_judge(Request $request){
        if($request ->isMethod('post')){
            $user_id   = $request ->input('user_id');
            $data      = DB::table('user') ->where('user_id',$user_id) ->get();
            foreach ($data as $value){
                $da  = array('user_status'=>$value ->user_status);
            }
            $Array   = (object)array();
            if($data == true){
                return json::json('success','请注意查收是不是通过审核',$da);
            }else{
                return json::json('failure','获取数据失败',$Array);
            }
        }
    }


    public function upload(Request $request){
        if($request ->isMethod('post')){
            $image   = new upload();
            $file = $image ->up();

            for ($i=0; $i<count($file);$i++){
                $img   = $image ->value($file,$i);
                $da[]= url().'/'.$img;
            }
        }
        $value   = array(
            'image'       => $da
        );
        return json::json('success','恭喜您图片上传成功',$value);
    }

    public function hx_register($username,$password,$nickname)
    {
        $url = $this->url . "/users";
        $data = array(
            'username' => $username,
            'password' => $password,
            'nickname' => $nickname
        );
        $header = array(
            'Content-Type: application/json',
            'Authorization: Bearer ' . $this->token
        );
        return $this->curl($url, $data, $header, "POST");

    }

    public function hx_user_update_password($username,$newpassword)
    {

        $url = $this->url . "/users/{$username}/password";
        $header = array(
            'Authorization: Bearer ' . $this->token
        );
        $data['newpassword'] = $newpassword;
        return $this->curl($url, $data, $header, "PUT");

    }




    private function curl($url, $data, $header = false, $method = "POST")
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if ($header) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        if ($data) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $ret = curl_exec($ch);
        return $ret;
    }



}


